const db = require('../db/connMysql');

const userDao = {
    /*
     * 用户使用工号密码登录的方法
     */
    async loginByWorkId(workId, password) {
        console.log('【开始连接数据库的时间】', Date());
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                console.log('【数据库连接成功的时间】', Date());
                let sql = `select
                               uid, username, UserType.name as userType, allowLogin
                           from
                               Users
                           left join
                               UserType
                           on UserType.userTypeId = Users.userTypeId
                           where workId = ? and password = ? Limit 1`;
                connection.query(sql, [workId, password], function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;
    }
};

module.exports = userDao;
